package com.weizhi.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.weizhi.server.dto.ResourceDto;
import com.weizhi.server.entity.Resource;
import com.weizhi.server.mapper.ResourceMapper;
import com.weizhi.server.service.ResourceService;
import com.weizhi.server.util.PropertyCopyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ResourceServiceImpl implements ResourceService {
    private final static Logger logger = LoggerFactory.getLogger(ResourceServiceImpl.class);

    @javax.annotation.Resource
    private ResourceMapper resourceMapper;

    @Override
    public PageInfo list(JSONObject param) {
        PageHelper.startPage(param.getInteger("pageIndex"), param.getInteger("pageSize"));
        List<Resource> resourceList = resourceMapper.list();
        PageInfo pageInfo = new PageInfo(resourceList);
        List<ResourceDto> resourceDtoList = PropertyCopyUtil.copyList(resourceList, ResourceDto.class);
        pageInfo.setList(resourceDtoList);
        return pageInfo;
    }

    @Override
    public List<ResourceDto> all() {
        List<Resource> resourceList = resourceMapper.list();
        List<ResourceDto> resourceDtoList = PropertyCopyUtil.copyList(resourceList, ResourceDto.class);



        return resourceDtoList;
    }

    @Override
    public List<ResourceDto> tree() {
        // 获取所有一级资源
        List<Resource> resourceList = resourceMapper.selectByParentId(0L);
        List<ResourceDto> resourceDtoList = PropertyCopyUtil.copyList(resourceList, ResourceDto.class);

        // 获取一级资源下的二级资源
        for(ResourceDto resourceDto: resourceDtoList) {
            resourceDto.setChildrenList(
                PropertyCopyUtil.copyList(resourceMapper.selectByParentId(resourceDto.getId()), ResourceDto.class)
            );
        }
        return resourceDtoList;
    }

    @Override
    public void save(ResourceDto resourceDto) {
        Resource resource = new Resource();
        BeanUtils.copyProperties(resourceDto, resource);
        if(resource.getId() == null){
            resourceMapper.insertSelective(resource);
        }else{
            resourceMapper.updateByPrimaryKey(resource);
        }

    }

    @Override
    @Transactional
    public void delete(Long id) {
        resourceMapper.deleteByPrimaryKey(id);
    }
}
